import dayjs from 'dayjs';

const SEC = 1000;
const MIN = 1 * 60 * SEC;
const HOUR = MIN * 60;
const DAY = HOUR * 24;

// 日期格式化
export const dateFormat = (timestamp, template = 'YYYY/MM/DD HH:mm:ss') => {
  return dayjs(timestamp).format(template);
};

// 时间戳转换为分钟
export const millisecondToMin = timestamp => {
  return Math.floor(timestamp / MIN);
};

// 时间前置补0
export function checkTime(i) {
  const len = 9;
  return `${i > len ? '' : 0}${i}`;
}
// 时间倒计时
export function getCountDwon(leftTime = 0) {
  return {
    day: checkTime(Math.floor(leftTime / DAY)),
    hour: checkTime(Math.floor((leftTime / HOUR) % 24)),
    minute: checkTime(Math.floor((leftTime / MIN) % 60)),
    second: checkTime(Math.floor((leftTime / SEC) % 60)),
  };
}

// 获取 date 实例
const getDateInstance = (() => {
  let date = null;
  return function () {
    if (date) {
      return date;
    }
    const instance = new Date();
    instance.setHours(0);
    instance.setMinutes(0);
    instance.setSeconds(0);
    instance.setMilliseconds(0);
    return (date = instance);
  };
})();

/**
 * @param {*} timestamp
 * isSameNaturalDay
 * 判断是同一个自然日
 * 只要当前消息日期在当天开始时间和结束时间范围之内就满足
 * 例如 2020/9/07 00:00:00 2020/9/7 23:59:59
 */
function isSameNaturalDay(timestamp) {
  const date = getDateInstance();
  const startTime = date.getTime();
  const endTime = startTime + DAY;
  return timestamp > startTime && timestamp < endTime;
}
/**
 * @param {*} timestamp
 * 判断是昨天，其实只要当前日期减去一天即可.
 */
function isYesterday(timestamp) {
  const date = getDateInstance();
  const endTime = date.getTime();
  const startTime = endTime - DAY;
  return timestamp > startTime && timestamp < endTime;
}

/**
 * @param {*} timestamp
 */

export const isFiveMinutesAge = timestamp => {
  const t = Date.now() - timestamp;
  return t < 5 * MIN;
};

/**
 * @param {时间戳(单位毫秒)} timestamp
 *  规则
 *  (t= 当前时间 - 最后一条消息发送/接收时间)
 *  1、t<1min时，显示“刚刚”
 *  2、1min <t <60min  ,显示“t分钟前”
 *  3、t>=60 且最后一条消息时间与当前时间属于同一个自然日，显示“时：分：秒”
 *  4、最后一条消息发生在上个自然日，显示“昨天 时：分：秒”
 *  5、其他，显示“年/月/日  时：分：秒”
 */
export const formatTime = timestamp => {
  if (!Number.isInteger(timestamp)) {
    return timestamp;
  }
  let formatStr = '';
  const t = Date.now() - timestamp;
  if (t < MIN) {
    formatStr = '刚刚';
  } else if (MIN < t && t < HOUR) {
    formatStr = `${millisecondToMin(t)}分钟前`;
  } else if (isSameNaturalDay(timestamp)) {
    formatStr = dateFormat(timestamp, 'HH:mm:ss');
  } else if (isYesterday(timestamp)) {
    formatStr = `昨天 ${dateFormat(timestamp, 'HH:mm:ss')}`;
  } else {
    formatStr = `${dateFormat(timestamp, 'YYYY/MM/DD')}`;
  }
  return formatStr;
};
